<?php

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

if (!function_exists('price')) {
    function price($price)
    {
        return sprintf('%.2f', $price);
    }
}

if (!function_exists('coupon')) {
    function coupon()
    {
        return \Illuminate\Support\Str::upper(md5(str_random()));
    }
}

if (!function_exists('randArray')) {
    function randArray($array, $number = 1)
    {
        $keys = array_rand($array, $number);
        $return = [];
        if ($number > 1) {
            foreach ($keys as $key) {
                $return[] = $array[$key];
            }
        } else {
            $return = $array[$keys];
        }

        return $return;
    }
}

if (!function_exists('password')) {
    function password($key, $request = null)
    {
        $request = $request ?: request();
        if (is_array($key)) {
            return $request->all($key);
        } else {
            return $request->input($key);
        }
    }
}

if (!function_exists('skuHashKey')) {
    function skuHashKey($data)
    {
        sort($data);
        return \Illuminate\Support\Str::upper(md5(implode($data, ':')));
    }
}

if (!function_exists('envIsProduction')) {
    function envIsProduction()
    {
        return app()->environment('production') ? true : false;
    }
}

if (!function_exists('getAllAddress')) {
    function getAllAddress($addressArray)
    {
        return $addressArray['province'] . $addressArray['city'] . $addressArray['district'] . $addressArray['address'];
    }
}

if (!function_exists('getHostFromFullPath')) {
    function getHostFromFullPath($url)
    {
        if (Str::startsWith($url, "https://")) {
            $prefix = "https://";
        } else {
            $prefix = "http://";
        }

        $url = Str::replaceFirst($prefix, "", $url);

        return $prefix . Str::before($url, "/");
    }
}

function about($key, $default = '')
{
    $data = \App\Models\About::where('meta_key', $key)->first();

    return $data ? $data->meta_value : $default;
}

function isCollectionProduct($id, $guard = 'api')
{
    if ($user = Auth::guard($guard)->user()) {
        $ids = (array)$user->collection_product_ids;
    } else {
        $ids = [];
    }

    return in_array($id, $ids);
}

function authUsername()
{
    return \Illuminate\Support\Facades\Auth::user()->name;
}

function authUserId()
{
    return \Illuminate\Support\Facades\Auth::id();
}
